package com.csp.mingyue.push.controller;

import cn.hutool.core.util.RandomUtil;
import com.csp.mingyue.common.core.constant.CacheConstants;
import com.csp.mingyue.common.core.constant.Constants;
import com.csp.mingyue.common.core.vo.R;
import com.csp.mingyue.common.email.support.EmailProperties;
import com.csp.mingyue.common.email.utils.EmailUtils;
import com.csp.mingyue.common.redis.utils.RedisUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import java.time.Duration;

/**
 * 邮箱服务
 *
 * @author njy
 * @date 2023/9/1 17:37
 */
@Slf4j
@Tag(name = "邮箱服务模块")
@Validated
@RestController
@RequestMapping("email")
@RequiredArgsConstructor
public class EmailController {

	private final EmailProperties emailProperties;

	/**
	 * 邮箱验证码
	 * @param email 邮箱
	 */
	@GetMapping("/code")
	@Operation(summary = "邮箱验证码", parameters = { @Parameter(name = "email", description = "邮箱", required = true) })
	public R<Void> emailCode(@Valid @NotBlank(message = "邮箱不能为空") String email) {
		if (!emailProperties.getEnabled()) {
			return R.fail("当前系统没有开启邮箱功能！");
		}
		String key = CacheConstants.CAPTCHA_CODE_KEY + email;
		String code = RandomUtil.randomNumbers(4);
		RedisUtils.setCacheObject(key, code, Duration.ofMinutes(Constants.CAPTCHA_EXPIRATION));
		try {
			EmailUtils.sendText(email, "登录验证码",
					"您本次验证码为：" + code + "，有效性为" + Constants.CAPTCHA_EXPIRATION + "分钟，请尽快填写。");
		}
		catch (Exception e) {
			log.error("验证码邮箱发送异常 => {}", e.getMessage());
			return R.fail(e.getMessage());
		}
		return R.ok();
	}

}
